package com.first.order.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.first.common.pojo.EduChapter;
import com.first.common.pojo.EduVideo;
import com.first.order.dao.EduChapterDao;
import com.first.order.dao.EduVideoDao;
import com.first.order.service.ChapterService;
import com.first.order.vo.EduChapterVo;
import com.first.order.vo.InsertChapterWithCourseIdVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * @program: finrsteducation-parent
 * @description:
 * @author: 张玉森
 * @create: 2023-06-06 11:30
 **/
@Service
public class ChapterServiceImpl implements ChapterService {
    @Autowired
    private EduChapterDao eduChapterDao;
    @Autowired
    private EduVideoDao eduVideoDao;

    @Override
    public List<EduChapter> findChapterById(String id) {
        QueryWrapper<EduChapter> wrapper = new QueryWrapper<>();
        wrapper.eq("ch.course_id", id);
        //wrapper.orderByAsc("ch.sort");
        return eduChapterDao.selectChapterById(wrapper);
    }

    @Override
    public Integer insertChapterWithCourseId(InsertChapterWithCourseIdVo chapterWithCourseIdVo) {
        EduChapter eduChapter = new EduChapter();
        eduChapter.setCourseId(chapterWithCourseIdVo.getCourseId());
        eduChapter.setTitle(chapterWithCourseIdVo.getTitle());
        eduChapter.setGmtModified(LocalDateTime.now());
        if (Objects.equals(chapterWithCourseIdVo.getId(), "") || chapterWithCourseIdVo.getId() == null) {
            eduChapter.setId(RandomUtil.randomNumbers(19));
            eduChapter.setSort(chapterWithCourseIdVo.getSort());
            eduChapter.setGmtCreate(LocalDateTime.now());
            return eduChapterDao.insert(eduChapter);
        }
        eduChapter.setId(chapterWithCourseIdVo.getId());
        return eduChapterDao.updateById(eduChapter);
    }

//    @Override
//    public Integer insertChapterWithCourseId(EduChapterVo eduChapterVo) {
//        EduChapter eduChapter = new EduChapter();
//        eduChapter.setId(eduChapterVo.getId());
//        eduChapter.setTitle(eduChapterVo.getTitle());
//        eduChapter.setGmtModified(LocalDateTime.now());
//        int i = eduChapterDao.updateById(eduChapter);
//        return i;
//    }

    @Override
    public Integer deleteChapterWithCourseId(EduChapterVo eduChapterVo) {
        QueryWrapper<EduChapter> wrapper2 = new QueryWrapper<>();
        wrapper2.eq("id", eduChapterVo.getId());
        int i = eduChapterDao.delete(wrapper2);

        QueryWrapper<EduVideo> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id", eduChapterVo.getCourse_id());
        eduVideoDao.delete(wrapper);

        return i;
    }
}
